package com.xiaoqi.controller;

import com.alibaba.dubbo.config.annotation.Reference;

import com.xiaoqi.constant.MessageConstant;
import com.xiaoqi.constant.RedisMessageConstant;
import com.xiaoqi.pojo.Member;
import com.xiaoqi.pojo.Result;
import com.xiaoqi.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author PC
 * creationTime: 2022/11/22 12:18
 */
@RequestMapping("/login")
@RestController
public class LoginController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    /**
     * 手机快速登录
     * @param loginInfo
     * @param response
     * @return
     */
    @PostMapping("/check")
    public Result check(@RequestBody Map<String,String> loginInfo, HttpServletResponse response){
        //获取jedis对象
        Jedis jedis = jedisPool.getResource();
        //用户输入的手机号码
        String telephone = loginInfo.get("telephone");
        //用户输入的验证码
        String validateCode = loginInfo.get("validateCode");
        //组成key
        String key = RedisMessageConstant.SENDTYPE_LOGIN+"_"+telephone;
        //通过key来查询redis中是否有验证码
        String codeInDb = jedis.get("key");
        //判断是否有验证码
        //没有验证码，验证码失效或者没有发送
        if (StringUtils.isEmpty(codeInDb)){
            return new Result(false, MessageConstant.RESENT_VALIDATECODE);
        }
        //有验证码判断验证码是否一致
        //不一致
        if (!validateCode.equals(codeInDb)){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //关闭jedis
        jedis.close();
        //验证码一直通过手机号码插叙手机号是否注册会员
        Member memberInDB = memberService.findByTelephone(telephone);
        //如果不是会员则注册会员
        if (null==memberInDB){
            Member member = new Member();
            member.setBirthday(new Date());
            member.setPhoneNumber(telephone);
            member.setRemark("手机快速注册");
            memberService.add(member);
        }
        //创建cookie对象的一个值为名字第二个为值
        Cookie cookie = new Cookie("login_member_telephone",telephone);
        //设置cookie的失效时间为一个月
        cookie.setMaxAge(60*60*24*30);
        // 访问的路径 根路径下时 网站的所有路径 都会发送这个cookie
        cookie.setPath("/");
        //添加cookie
        response.addCookie(cookie);
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
